package com.cxp.serverdemo.config;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.access.AccessDecisionManager;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.authentication.AnonymousAuthenticationToken;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.InsufficientAuthenticationException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.stereotype.Component;

import java.util.Collection;
import java.util.Iterator;

/**
 * decide方法的三个参数中：
 * authentication：包含了当前的用户信息，包括拥有的权限。这里的权限来源就是前面登录时UserDetailsService中设置的authorities
 * object：就是FilterInvocation对象，可以得到request等web资源
 * configAttributes：是本次访问需要的权限，从CustomMetadataSource返回获取
 * 这里通过两层循环嵌套来确认当前用户所访问资源是否可以访问
 * 第一层 while (iterator.hasNext())：cas是由CustomMetadataSource（资源授权列表）获取的当前请求所要求的权限
 * 第二层 for (GrantedAuthority authority : authorities)：authorities是由Authentication（用户权限列表）获取的当前用户所拥有的权限
 * return：当确认通过或非法请求（例如用户输入不存在的地址）则返回，否则抛出异常
* */
@Component
public class CustomAccessDecisionManager implements AccessDecisionManager {

    private static final Logger logger = LoggerFactory.getLogger(CustomAccessDecisionManager.class);

    @Override
    public void decide(Authentication auth, Object o, Collection<ConfigAttribute> cas) throws AccessDeniedException, InsufficientAuthenticationException {
        logger.info("CustomAccessDecisionManager.cas-----" + cas.toString());
        Iterator<ConfigAttribute> iterator = cas.iterator();
        while (iterator.hasNext()) {
            ConfigAttribute ca = iterator.next();
            logger.info("CustomAccessDecisionManager.cas.ca-----" + ca.toString());
            //当前请求需要的权限
            String needRole = ca.getAttribute();
            if ("ROLE_LOGIN".equals(needRole)) {//当没有匹配的权限时（即非法URL），先判断是否匿名访问，是则抛出异常
                if (auth instanceof AnonymousAuthenticationToken) {
                    throw new BadCredentialsException("未登录");
                } else
                    return;//这里控制可能有问题
            }
            //当前用户所具有的权限
            Collection<? extends GrantedAuthority> authorities = auth.getAuthorities();
            logger.info("CustomAccessDecisionManager.authorities-----------" + authorities.toString());
            for (GrantedAuthority authority : authorities) {//这里采取的是开放原则 ，即只要用户有一个角色符合资源权限则放行
                logger.info("CustomAccessDecisionManager.authorities/needRole-----------" + authority.getAuthority() +"/"+ needRole);
                if (authority.getAuthority().equals(needRole)) {
                    return;
                }
            }
        }
        throw new AccessDeniedException("权限不足!");
    }

    @Override
    public boolean supports(ConfigAttribute configAttribute) {
        return false;
    }

    @Override
    public boolean supports(Class<?> aClass) {
        return false;
    }
}
